package com.facedemo.activity;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.facedemo.MyApplication;
import com.facedemo.R;
import com.facedemo.bean.FaceFeature;
import com.facedemo.db.entity.Person;
import com.facedemo.db.entity.PersonFeature;
import com.facedemo.db.utils.PersonDaoUtils;
import com.facedemo.db.utils.PersonFeatureDaoUtils;
import com.facedemo.face.FaceInfoManger;
import com.facedemo.utils.ImageUtils;
import com.facedemo.utils.LogUtils;

import net.facelib.mtfsdk.FaceApiMtfV2Android;
import net.gdface.sdk.CodeInfo;
import net.gdface.sdk.NotFaceDetectedException;

import java.io.File;

public class MainActivity extends Activity {
    private Button bt_more_enroll, bt_more_identify, bt_more_info,bt_setting,bt_register_from_photo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        bt_more_enroll = findViewById(R.id.bt_light_more_enroll);
        bt_more_identify = findViewById(R.id.bt_light_more_identify);
        bt_more_info = findViewById(R.id.bt_light_more_info);
        bt_setting = findViewById(R.id.bt_setting);
        bt_register_from_photo = findViewById(R.id.bt_register_from_photo);

        bt_more_enroll.setOnClickListener(onClickListener);
        bt_more_identify.setOnClickListener(onClickListener);
        bt_more_info.setOnClickListener(onClickListener);
        bt_setting.setOnClickListener(onClickListener);
        bt_register_from_photo.setOnClickListener(onClickListener);
    }

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.bt_light_more_identify://人脸识别
                    Intent intent2 = new Intent(MainActivity.this, FaceDetectActivity.class);
                    startActivity(intent2);
                    break;
                case R.id.bt_light_more_enroll://人脸注册
                    showRegisterDialog(MainActivity.this);
                    break;
                case R.id.bt_light_more_info://用户信息
                    Intent intent3 = new Intent(MainActivity.this, UserInfoActivity.class);
                    startActivity(intent3);
                    break;
                case R.id.bt_register_from_photo://批量导入
                    registerFromPhoto();
                    break;
                case R.id.bt_setting://设置
                    Intent intent4 = new Intent(MainActivity.this, SettingActivity.class);
                    startActivity(intent4);
                    break;
                default:
                    break;
            }
        }
    };

    private void showRegisterDialog(Context context) {
        final LayoutInflater inflater = LayoutInflater.from(this);
        final View textEntryView = inflater.inflate(R.layout.item_edittext, null);
        final EditText et_id = (EditText) textEntryView.findViewById(R.id.et_id);
        final EditText et_name = (EditText) textEntryView.findViewById(R.id.et_name);

        final AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setCancelable(false);
        builder.setTitle("请输入注册信息 : ");
        builder.setView(textEntryView);
        builder.setPositiveButton("确认",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String id = et_id.getText().toString().trim();
                        if (0 == id.length()) {
                            Toast.makeText(MainActivity.this, "请输入ID", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        String name = et_name.getText().toString().trim();
                        if (0 == name.length()) {
                            Toast.makeText(MainActivity.this, "请输入名字", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        Person employee = PersonDaoUtils.queryById(id);
                        if(employee!=null) {
                            Toast.makeText(MainActivity.this, "此ID已经注册", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        Intent intent = new Intent(MainActivity.this, FaceRegisterActivity.class);
                        intent.putExtra("personId", id);
                        intent.putExtra("name", name);
                        startActivity(intent);
                        dialog.dismiss();
                    }
                });
        builder.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.dismiss();
                    }
                });
        AlertDialog dialog = builder.create();
        dialog.getWindow().setGravity(Gravity.CENTER);
        dialog.show();
    }

    private boolean isRegistering = false;
    //批量导入
    private void registerFromPhoto() {
        if(isRegistering) return;
        isRegistering = true;

        bt_more_enroll.setEnabled(false);
        bt_more_identify.setEnabled(false);
        bt_more_info.setEnabled(false);
        bt_register_from_photo.setText("正在导入...");
        bt_register_from_photo.setEnabled(false);

        new Thread(new Runnable() {
            @Override
            public void run() {
                File faceFileDir = new File(Environment.getExternalStorageDirectory().getPath() + "/FaceRegister");
                if (!faceFileDir.exists()) {
                    faceFileDir.mkdirs();
                }
                File[] faceFiles = faceFileDir.listFiles();
                if(faceFiles==null || faceFiles.length==0) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            registerFinish();
                        }
                    });
                    return;
                }
                int succseeNum = 0;
                int failedNum = 0;
                for(File faceFile:faceFiles) {
                    Bitmap bitmap = BitmapFactory.decodeFile(faceFile.getAbsolutePath());
                    try {
                        CodeInfo[] codeInfos = FaceApiMtfV2Android.getInstance().detectAndGetCodeInfo(bitmap,1);
                        if(codeInfos==null || codeInfos.length==0) {
                            failedNum++;
                            LogUtils.printE("提取人脸特征失败："+faceFile.getAbsolutePath());
                            continue;
                        } else {
                            succseeNum++;
                            LogUtils.printD("提取人脸特征成功："+faceFile.getAbsolutePath());

                            //保存图片
                            String personId = faceFile.getName();
                            int lastDot = personId.lastIndexOf(".");
                            if(lastDot>0 && lastDot<personId.length()){
                                personId = personId.substring(0,lastDot);
                            }

                            int faceId = 1;
                            String path = MyApplication.DIR_PATH + personId + "_" + faceId + ".jpg";
                            ImageUtils.save(bitmap,path,Bitmap.CompressFormat.JPEG,false);

                            //保存人员到数据库
                            Person person = new Person();
                            person.setPersonId(personId);
                            person.setName(personId);
                            PersonDaoUtils.addOrUpdate(person);

                            //保存人脸到数据库
                            PersonFeature pf = new PersonFeature();
                            pf.setPersonId(personId);
                            pf.setFaceId(faceId);
                            pf.setFeature(codeInfos[0].getCode());
                            pf.setFacePicPath(path);
                            PersonFeatureDaoUtils.addOrUpdate(pf);

                            //添加人脸到人脸库
                            FaceFeature ff = new FaceFeature();
                            ff.personId = personId;
                            ff.faceId = faceId;
                            ff.feature = codeInfos[0].getCode();
                            FaceInfoManger.getInstance().addOrUpdateFace(ff);
                        }
                    } catch (NotFaceDetectedException e) {
                        e.printStackTrace();
                    }
                }
                final String msg = "成功："+succseeNum+" 失败："+failedNum;
                LogUtils.printD(msg);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this,msg,Toast.LENGTH_LONG).show();
                        registerFinish();
                    }
                });

            }
        }).start();
    }

    private void registerFinish() {
        isRegistering = false;
        bt_more_enroll.setEnabled(true);
        bt_more_identify.setEnabled(true);
        bt_more_info.setEnabled(true);
        bt_register_from_photo.setText("批量导入");
        bt_register_from_photo.setEnabled(true);
    }


    //-------------------关闭-------------------------------------
    private long exitTime = 0;// 计算短时间内点击返回按钮的次数
    /** 点击返回按钮2次，退出应用程序 */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(MainActivity.this,"再点一次，退出应用程序",Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                onDestroy();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}